/* 
** (Copyright) sejishikong <sejishikong@263.net>
** Authors:    sejishikong <sejishikong@263.net>
**             Wei Lian <lianwei2003.student@sina.com> 
** Maintainer: Wei Lian
**    This program is free software; you can redistribute it and/or modify
**    it under the terms of the GNU General Public License Version 2 as
**    published by the Free Software Foundation;
**
**    This program is distributed in the hope that it will be useful,
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**    GNU General Public License for more details.
**
**    You should have received a copy of the GNU General Public License
**    along with this program; if not, write to the Free Software
**    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
*/

#include "header.h"
#include "menubar.h"
#include "mainwindow.h"
#include "mypopupmenu.h"
#include "mylistitem.h"
#include "config.h"
#include "fork.h"
#include "channel.h"
#include "record.h"
#include "timing.h"


MenuBar::MenuBar(QWidget * parent, const char *name):QMenuBar(parent,
							      name),
mainwindow(static_cast < Sopcast * >(parent))
{
    ///initialization
    QSettings settings;
    ///
    int id = 0;
    ///menu file
    menu_file = new QPopupMenu(this);
    menu_file->insertItem("Exit", qApp, SLOT(quit()), CTRL + Key_Q, 0);
    insertItem("&File", menu_file, id++);

    ///menu config
    menu_config = new QPopupMenu(this);
    menu_config->setCheckable(true);
    //language
    submenu_language = new QPopupMenu(this);
    submenu_language->setCheckable(true);
    submenu_language->insertItem("Chinese", 1);
    submenu_language->insertItem("English", 0);
    flag_language =
	settings.readBoolEntry("/qsopcast/enableChinese", false);
    submenu_language->setItemChecked(flag_language, true);
    connect(submenu_language, SIGNAL(activated(int)), this,
	    SLOT(onSwitchLanguage(int)));
    menu_config->insertItem("Language", submenu_language, LANGUAGE);
    //channel color
    submenu_color = new QPopupMenu(this);
    submenu_color->setCheckable(true);
    submenu_color->insertItem("User", USER_COLUMN);
    submenu_color->insertItem("Visit", VISIT_COLUMN);
    submenu_color->insertItem("Qs", QS_COLUMN);
    submenu_color->insertItem("Qc", QC_COLUMN);
    submenu_color->insertItem("Kbps", KBPS_COLUMN);
    color_column =
	settings.readNumEntry("/qsopcast/ChannelColor", USER_COLUMN);
    submenu_color->setItemChecked(color_column, true);
    connect(submenu_color, SIGNAL(activated(int)), this,
	    SLOT(onSwitchColor(int)));
    menu_config->insertItem("Channel Color", submenu_color, CHANNEL_COLOR);
    //show null channel
    menu_config->insertItem("&Show Null Channel", this,
			    SLOT(onNullChannelToggled()), CTRL + Key_N,
			    NULL_CHANNEL);
    menu_config->setItemChecked(NULL_CHANNEL,
				settings.
				readBoolEntry("/qsopcast/shownullchannels",
					      FALSE));
    //enabel channel sorting
    menu_config->insertItem("&Enable Channel Sorting", this,
			    SLOT(onChannelSortToggled()), CTRL + Key_S,
			    CHANNEL_SORT);
    menu_config->setItemChecked(CHANNEL_SORT,
				settings.
				readBoolEntry
				("/qsopcast/enablechannelsorting", FALSE));
    //configuration
    menu_config->insertItem("&Config", this, SLOT(onconfigclicked()),
			    CTRL + Key_F, CONFIG);
    insertItem("&Config", menu_config, id++);

    ///menu history
    history = new QPopupMenu(this);
    history->insertItem("&Clear", this, SLOT(clearHistory()), CTRL + Key_K,
			0);
    history->insertSeparator();
    connect(history, SIGNAL(activated(int)), this,
	    SLOT(onChooseHistory(int)));
    insertItem("&History", history, id++);

    ///menu bookmark
    bookmark = new MyPopupMenu(this);
    bookmark->insertItem("&Add", this,
			 SLOT(addToBookmark()), CTRL + Key_B, 0);
    bookmark->insertSeparator();
    connect(bookmark, SIGNAL(activated(int)), this,
	    SLOT(onChooseBookmark(int)));
    insertItem("&Bookmark", bookmark, id++);

    ///menu help
    menu_help = new QPopupMenu(this);
    menu_help->insertItem("&About", this, SLOT(about()), CTRL + Key_H, 0);
    insertItem("&Help", menu_help, id++);

}


MenuBar::~MenuBar()
{
    QSettings settings;
    settings.writeEntry("/qsopcast/enableChinese", flag_language);
    settings.writeEntry("/qsopcast/shownullchannels",
			menu_config->isItemChecked(NULL_CHANNEL));
    settings.writeEntry("/qsopcast/enablechannelsorting",
			menu_config->isItemChecked(CHANNEL_SORT));
    settings.writeEntry("/qsopcast/ChannelColor", color_column);

}


void MenuBar::clearHistory()
{
    for (int index = history->count() - 1; index >= 2; index--) {
	history->removeItemAt(index);
    }
}

void MenuBar::onSwitchColor(int id)
{
    mainwindow->channel->switchChannelColor(id);
    color_column = id;
    for (uint index = 0; index < submenu_color->count(); index++)
	submenu_color->setItemChecked(submenu_color->idAt(index), false);
    submenu_color->setItemChecked(id, true);
}


void MenuBar::onChannelSortToggled()
{
    menu_config->setItemChecked(CHANNEL_SORT,
				!menu_config->isItemChecked(CHANNEL_SORT));
    mainwindow->channel->toggleChannelSort();
}


void MenuBar::onNullChannelToggled()
{
    menu_config->setItemChecked(NULL_CHANNEL,
				!menu_config->isItemChecked(NULL_CHANNEL));
    mainwindow->channel->toggleNullChannel();
}


void MenuBar::onconfigclicked()
{
    mainwindow->vboxconfig->
	move(mapToGlobal
	     (QPoint
	      ((mainwindow->width() - mainwindow->vboxconfig->width()) / 2,
	       (mainwindow->height() -
		mainwindow->vboxconfig->height()) / 2)));
    mainwindow->vboxconfig->show();

}


void MenuBar::onChooseHistory(int id)
{
//    printf("history index=%d,id=%d\n", history->indexOf(id), id);
    if (id >= 2) {
	QString str = history->text(id);
	QString name = str.mid(0,
			       str.find(mainwindow->vboxconfig->
					editchannelheader->text()) - 1);
	QString url =
	    str.mid(str.
		    find(mainwindow->vboxconfig->editchannelheader->
			 text()));
	//launch sop
	mainwindow->fork->killsop();
	mainwindow->fork->killplayer();
	if (mainwindow->fork->forksop(url, name) == TRUE) {
	} else
	    fprintf(stderr, "failed to launch sp-sc!\n");
    }
}


void MenuBar::onChooseBookmark(int id)
{
//    printf("bookmark index=%d,id=%d\n", bookmark->indexOf(id), id);
    if (id >= 2) {
	if (bookmark->rightbutton)	///delete
	{
	    bookmark->removeItem(id);
	} else			///launch
	{
	    QString str = bookmark->text(id);
	    QString name = str.mid(0,
				   str.find(mainwindow->vboxconfig->
					    editchannelheader->text()) -
				   1);
	    QString url =
		str.mid(str.
			find(mainwindow->vboxconfig->editchannelheader->
			     text()));
	    //launch sop
	    mainwindow->fork->killsop();
	    mainwindow->fork->killplayer();
	    if (mainwindow->fork->forksop(url, name) == TRUE) {
		///add to history
		addToPopupMenu(history, url, name);

	    } else
		fprintf(stderr, "failed to launch sp-sc!\n");
	}
    }
}


void MenuBar::addToPopupMenu(QPopupMenu * menu, QString url, QString name)
{
    if (menu->count() == 2)	///no item
	menu->insertItem(name + " " + url, 2);
    else if (menu->count() > 2) {
	bool flag = FALSE;
	uint index;
	for (index = 2; index < menu->count(); index++) {
	    QString str = menu->text(menu->idAt(index));
	    QString str_name = str.mid(0,
				       str.find(mainwindow->vboxconfig->
						editchannelheader->
						text()) - 1);
	    QString str_url =
		str.mid(str.
			find(mainwindow->vboxconfig->editchannelheader->
			     text()));
	    if (url == str_url) {
		if (name != str_name) {
		    menu->changeItem(menu->idAt(index), name + " " + url);
		}
		flag = TRUE;
		break;
	    }
	}
	if (flag == FALSE)
	    menu->insertItem(name + " " + url, menu->idAt(index - 1) + 1);
    } else
	fprintf(stderr, "err: count<2\n");
}


void MenuBar::addToBookmark()
{
    QListViewItem *item = mainwindow->channel->currentItem();
    if (item == 0)
	return;
    if (item->depth() == 1)
	addToPopupMenu(bookmark, item->text(URL_COLUMN),
		       item->text(NAME_COLUMN));
}


#include "mozart.xpm"
void MenuBar::about()
{
    const QPixmap p1(mozart);
    QMessageBox m;
    m.setCaption("qsopcast");
    m.setIconPixmap(p1);
    m.setText("qsopcast: a QT front-end to p2p TV sopcast.\n"
	      "(c)2005-2006 Liu Di. All rights reserved.\n"
	      "Maintainer: Wei Lian\n"
	      "Developers: Liu Di, Wei Lian\n"
	      "http://lianwei3.googlepages.com/home2");
    m.exec();
}

void MenuBar::onSwitchLanguage(int id)
{
    flag_language = id;
    for (uint index = 0; index < submenu_language->count(); index++)
	submenu_language->setItemChecked(submenu_language->idAt(index),
					 false);
    submenu_language->setItemChecked(id, true);

    if (id == 1) {
	mainwindow->buttonchannel->
	    setTextLabel(QString::fromUtf8("频道"));
	mainwindow->buttonsearch->
	    setTextLabel(QString::fromUtf8("搜索"));
	mainwindow->buttonexpand->
	    setTextLabel(QString::fromUtf8("展开"));
	mainwindow->buttonplayer->
	    setTextLabel(QString::fromUtf8("播放器"));
	mainwindow->buttonstop->setTextLabel(QString::fromUtf8("停止"));
	mainwindow->record->buttonrecord->
	    setTextLabel(QString::fromUtf8("录制"));
	changeItem(0, QString::fromUtf8("文件"));
	changeItem(1, QString::fromUtf8("设置"));
	changeItem(2, QString::fromUtf8("历史"));
	changeItem(3, QString::fromUtf8("书签"));
	changeItem(4, QString::fromUtf8("帮助"));
	menu_file->changeItem(0, QString::fromUtf8("退出"));
	menu_config->changeItem(LANGUAGE, QString::fromUtf8("语言"));
	menu_config->changeItem(CONFIG, QString::fromUtf8("设置"));
	history->changeItem(0, QString::fromUtf8("清除"));
	bookmark->changeItem(0, QString::fromUtf8("加入"));
	menu_help->changeItem(0, QString::fromUtf8("关于"));
	mainwindow->record->timing->label_timing->
	    setText(QString::fromUtf8(" 定时(小时:分钟) "));

    } else {
	mainwindow->buttonchannel->setTextLabel("Channel");
	mainwindow->buttonsearch->setTextLabel("Search");
	mainwindow->buttonexpand->setTextLabel("Expand");
	mainwindow->buttonplayer->setTextLabel("Player");
	mainwindow->buttonstop->setTextLabel("Stop");
	mainwindow->record->buttonrecord->setTextLabel("Record");
	changeItem(0, "&File");
	changeItem(1, "&Config");
	changeItem(2, "&History");
	changeItem(3, "&Bookmark");
	changeItem(4, "&Help");
	menu_file->changeItem(0, "Exit");
	menu_config->changeItem(LANGUAGE, "Language");
	menu_config->changeItem(CONFIG, "&Config");
	history->changeItem(0, "&Clear");
	bookmark->changeItem(0, "&Add");
	menu_help->changeItem(0, "&About");
	mainwindow->record->timing->label_timing->
	    setText(" Timing(hour:minute) ");
    }
}
